<?php
defined('IN_APP') or exit('No permission resources.');

gt_base::load_sys_func('dir');

/**
 * Class module_api
 * 模块安装操作
 */
class module_api{
    private $module, $install_dir, $uninstall_dir, $db;
    public $error_msg = '';

    public function __construct($module=''){
        $this->module = $module;
        $this->db = gt_base::load_model('Module');
    }

    public function install($module = ''){
        define('INSTALL', true);
        if($module)
            $this->module = $module;
        //安装文件夹
        $this->install_dir = $install_dir = dir_path(APP_PATH.DIRECTORY_SEPARATOR.$this->module.DIRECTORY_SEPARATOR.'install'.DIRECTORY_SEPARATOR);
        $this->check_file();
        //echo $this->install_dir;
        //执行sql文件
        $models = @require ($this->install_dir.'model.php');
        if(!is_array($models) || empty($models)){
            $models = array('module');
        }
        if(!in_array('module', $models)){
            array_unshift($models, 'module');
        }
        if(is_array($models) && !empty($models)){
            foreach($models as $v){
                $sql = file_get_contents($this->install_dir.$v.'.sql');
                $this->sql_execute($sql);
            }
        }
        if (file_exists($install_dir.'extention.inc.php')) {
            $menu_db = D('Menu');
            @include ($install_dir.'extention.inc.php');
        }
        $file = dir_path(APP_ROOT.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.'zh-cn'.DIRECTORY_SEPARATOR).'admin'.'.lang.php';
        if(file_exists($file)){

            $content = file_get_contents($file);
            $content = substr($content,0,-2);
            $data = '';
            foreach ($language as $key => $l) {
                $data .= "\$LANG['".$key."'] = '".$l."';\r\n";
            }
            $data = $content.$data."?>";
            file_put_contents($file,$data);
        }else{
            foreach ($language as $key =>$l) {
                $data .= "\$LANG['".$key."'] = '".$l."';\r\n";
            }
            $data = "<?"."php\r\n\$data?>";
            file_put_contents($file,$data);
        }
        //移动模板文件
        $from_dir = './Application/'.$this->module.'/View/';
        $to_dir = './Template/';
        dir_copy($from_dir, $to_dir);
    }

    public function uninstall($module=''){
        if (!$module) {
            $this->error_msg = LANG('illegal_parameters');
            return false;
        }
        $this->module = $module;
        $this->uninstalldir = dir_path(APP_PATH.DIRECTORY_SEPARATOR.$this->module.DIRECTORY_SEPARATOR.'uninstall'.DIRECTORY_SEPARATOR);
        if (!is_dir($this->uninstalldir)) {
            $this->error_msg = LANG('uninstall_dir_no_exist');
            return false;
        }
        if (file_exists($this->uninstalldir.'model.php')) {
            $models = @require($this->uninstalldir.'model.php');
            if (is_array($models) && !empty($models)) {
                foreach ($models as $m) {
                    if (!file_exists($this->uninstalldir.$m.'.sql')) {
                        $this->error_msg = $this->module.DIRECTORY_SEPARATOR.'uninstall'.DIRECTORY_SEPARATOR.$m.LANG('sql_no_exist');
                        return false;
                    }
                }
            }
        }
        if (is_array($models) && !empty($models)) {
            foreach ($models as $m) {
                $sql = file_get_contents($this->uninstalldir.$m.'.sql');
                $this->sql_execute($sql);
            }
        }
        if (file_exists($this->uninstalldir.'extention.inc.php')) {
            $menu_db = D('Menu');
            $module_db = D('Module');
            @include ($this->uninstalldir.'extention.inc.php');
        }
        //删除模板文件
        $del_path = './Template/'.$this->module.'/';
        dir_delete($del_path);
    }

    /**
     * @param string $module
     * @return bool
     * 检查安装文件是否齐全
     */
    public function check_file($module = ''){
        define('INSTALL', true);
        if($module)
            $this->module = $module;
        if(!$this->module){
            $this->error_msg = LANG('no_module');
            return false;
        }
        $one = $this->db->queryObj($this->module, 'module');
        if(!$one){
            $this->error_msg = LANG('this_module_installed');
            return false;
        }
        if (!$this->installdir) {
            $this->installdir = PC_PATH.'modules'.DIRECTORY_SEPARATOR.$this->module.DIRECTORY_SEPARATOR.'install'.DIRECTORY_SEPARATOR;
        }
        if(!is_dir($this->install_dir)){
            $this->error_msg = LANG('install_dir_no_exist');
            return false;
        }
        if (!file_exists($this->installdir.'module.sql')) {
            $this->error_msg = LANG('module_sql_no_exist');
            return false;
        }
        if (!file_exists($this->installdir.$this->module.'.sql')) {
            $this->error_msg = LANG('sql_no_exist');
            return false;
        }
        return true;
    }

    public function sql_execute($sql){
        $Model = new \Think\Model();
        $sqls = $this->sql_split($sql);
        if(is_array($sqls)){
            foreach($sqls as $item_sql){
                if(trim($item_sql) != ''){
                    $Model->execute($item_sql);
                }
            }
        }else{
            $Model->execute($sqls);
        }
        return true;
    }

    public function sql_split($sql){
        $ret = array();
        $num = 0;
        $table_pre = C('DB_PREFIX');
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach($queriesarray as $query){
            $ret[$num] = '';
            //替换换行
            $query = str_replace("\n",'',$query);
            //替换表前缀
            if($table_pre){
                $query = str_replace('gtx_',$table_pre,$query);
            }
            $ret[$num]  = $query;
            $num++;
        }
        return $ret;
    }
}